import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:google_mlkit_barcode_scanning/google_mlkit_barcode_scanning.dart';

import 'detector_view.dart';
import 'painters/barcode_detector_painter.dart';

class BarcodeScannerView extends StatefulWidget {
  @override
  State<BarcodeScannerView> createState() => _BarcodeScannerViewState();
}

class _BarcodeScannerViewState extends State<BarcodeScannerView> {
  final BarcodeScanner _barcodeScanner = BarcodeScanner();
  bool _canProcess = true;
  bool _isBusy = false;
  CustomPaint? _customPaint;
  String? _text;
  var _cameraLensDirection = CameraLensDirection.back;

  @override
  void dispose() {
    _canProcess = false;
    _barcodeScanner.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DetectorView(
      title: 'Barcode Scanner',
      customPaint: _customPaint,
      text: _text,
      onImage: _processImage,
      initialCameraLensDirection: _cameraLensDirection,
      onCameraLensDirectionChanged: (value) => _cameraLensDirection = value,
    );
  }

  Future<void> _processImage(InputImage inputImage) async {
    // 快速失败检查
    if (!_canProcess || _isBusy) return;

    _isBusy = true;

    try {
      // 延迟状态更新，避免不必要的重建
      if (_text!.isNotEmpty) {
        setState(() {
          _text = '';
        });
      }

      // 处理图像
      final barcodes = await _barcodeScanner.processImage(inputImage);

      // 如果有识别结果，处理显示逻辑
      if (barcodes.isNotEmpty) {
        await _handleBarcodeResults(barcodes, inputImage);
      } else {
        // 没有识别结果时的处理
        await _handleNoBarcodeResults();
      }

      // 添加处理间隔，避免过于频繁的处理
      if (barcodes.isNotEmpty) {
        await Future<void>.delayed(const Duration(milliseconds: 2000));
      } else {
        await Future<void>.delayed(const Duration(milliseconds: 500));
      }

    } catch (e) {
      debugPrint('Barcode processing error: $e');
      // 发生错误时也要重置状态
      _isBusy = false;
      if (mounted) {
        setState(() {
          _text = 'Processing error';
        });
      }
      return;
    }

    _isBusy = false;
  }

  /// 处理有识别结果的情况
  Future<void> _handleBarcodeResults(List<Barcode> barcodes, InputImage inputImage) async {
    if (inputImage.metadata?.size != null && inputImage.metadata?.rotation != null) {
      // 使用自定义绘制显示边界框
      final painter = BarcodeDetectorPainter(
        barcodes,
        inputImage.metadata!.size,
        inputImage.metadata!.rotation,
        _cameraLensDirection,
      );
      _customPaint = CustomPaint(painter: painter);
      _text = ''; // 清空文本显示
    } else {
      // 构建识别结果文本
      final text = StringBuffer('Barcodes found: ${barcodes.length}\n\n');
      for (final barcode in barcodes) {
        text.writeln('Barcode: ${barcode.rawValue}');
        text.writeln(); // 空行分隔
      }
      _text = text.toString();
      _customPaint = null;
    }

    // 只在 mounted 时更新 UI
    if (mounted) {
      setState(() {});
    }

    // 在结果处理后再添加一个短暂延迟
    await Future<void>.delayed(const Duration(milliseconds: 100));
  }

  /// 处理无识别结果的情况
  Future<void> _handleNoBarcodeResults() async {
    // 只有在之前有内容时才更新
    if (_text!.isNotEmpty || _customPaint != null) {
      _text = 'No barcodes found';
      _customPaint = null;

      if (mounted) {
        setState(() {});
      }
    }
  }
}
